"use strict";
cc._RF.push(module, 'e967fzAB6tDNbd1PakApO1V', 'starGame');
// script/star_project/starGame.js

"use strict";

// @ccclass('Tw')
cc.Class({
  "extends": cc.Component,
  properties: {
    layerReady: {
      "default": null,
      type: cc.Node
    },
    layerGame: {
      "default": null,
      type: cc.Node
    },
    layerZhanTing: {
      "default": null,
      type: cc.Node
    },
    prefab_block: {
      "default": null,
      type: cc.Prefab
    },
    prefab_star: {
      "default": null,
      type: cc.Prefab
    },
    block_parent: {
      "default": null,
      type: cc.Node
    },
    star_parent: {
      "default": null,
      type: cc.Node
    },
    node_ChuiZi: {
      "default": null,
      type: cc.Node
    }
  },
  // LIFE-CYCLE CALLBACKS:
  onLoad: function onLoad() {
    this.layerGame.active = false;
    this.layerReady.active = true;
    this.layerZhanTing.active = false; //创建星星相关数值

    this.black_size = 64;
    this.black_interval = 4;
    this.black_num_width = 10;
    this.black_num_height = 10; //开局隐藏

    this.node_ChuiZi.active = false; //声明角标二维数组

    this.arr_blocks = [];

    for (var i = 0; i < this.black_num_width; i++) {
      this.arr_blocks[i] = [];
    }

    this.clean(); //星星的容器大小

    this.Setparent(); //锤子
    //调用函数
    // this.createAllBlock();

    this.setTouch();
  },
  //设置父节点
  Setparent: function Setparent() {
    //星星的容器大小
    this.block_parent.width = (this.black_size + this.black_interval) * this.black_num_width + this.black_interval;
    this.block_parent.height = (this.black_size + this.black_interval) * this.black_num_height + this.black_interval;
    this.block_parent.y = -this.block_parent.parent.height / 2 + this.block_parent.height / 2 + 80;
    this.star_parent.width = this.block_parent.width;
    this.star_parent.height = this.block_parent.height;
    this.star_parent.y = this.block_parent.y;
  },
  start: function start() {},
  //创建所有星星
  createAllBlock: function createAllBlock() {
    //设置星星初始位置
    var block_strat_x = -this.block_parent.width / 2 + this.black_size / 2 + this.black_interval;
    var block_start_y = -this.block_parent.height / 2 + this.black_size / 2 + this.black_interval;

    for (var j = 0; j < this.black_num_height; j++) {
      for (var i = 0; i < this.black_num_width; i++) {
        var block = cc.instantiate(this.prefab_block);
        block.parent = this.block_parent;
        block.x = block_strat_x + i * (this.black_size + this.black_interval);
        block.y = block_start_y + j * (this.black_size + this.black_interval); //获得block的脚本文件

        var js_block = block.getComponent("block");
        var index_ran = Math.floor(Math.random() * 5);
        js_block.init(index_ran); // if(i==0 && j== 0){
        //     this.node_ChuiZi.setPosition(block.getPosition());
        //     console.log(this.node_ChuiZi.getPosition());
        // }
      }
    }

    this.refreshArr();
  },
  //通过元素块的坐标获得二维数据的角标
  getArrByPos: function getArrByPos(pos) {
    // console.log(pos);
    var x = this.block_parent.width / 2 + pos.x;
    var y = this.block_parent.height / 2 + pos.y;
    var xx = Math.floor(x / (this.black_size + this.black_interval));
    var yy = Math.floor(y / (this.black_size + this.black_interval)); //console.log("pos_x:",xx,"pos_y:",yy)

    return cc.v2(yy, xx);
  },
  //刷新二维数组
  refreshArr: function refreshArr() {
    for (var i = 0; i < this.black_num_height; i++) {
      for (var j = 0; j < this.black_num_width; j++) {
        this.arr_blocks[i][j] = -1;
      }
    }

    var child = this.block_parent.children; //获取子节点

    for (var _i = 0; _i < child.length; _i++) {
      var childPos = child[_i].getPosition();

      var pos_arr = this.getArrByPos(childPos);

      var type_block = child[_i].getComponent("block").blockType;

      this.arr_blocks[pos_arr.x][pos_arr.y] = type_block;
    } // console.log(this.arr_blocks);

  },
  //判断游戏是否结束
  isGameOver: function isGameOver() {
    for (var i = 0; i < this.black_num_height; i++) {
      for (var j = 0; j < this.black_num_width; j++) {
        if (this.arr_blocks[i][j] != -1) {
          if (i + 1 < this.black_num_height && this.arr_blocks[i + 1][j] == this.arr_blocks[i][j]) {
            return false;
          } else if (j + 1 < this.black_num_width && this.arr_blocks[i][j + 1] == this.arr_blocks[i][j]) {
            //判断是否相邻
            return false;
          } else if (i - 1 >= 0 && this.arr_blocks[i - 1][j] == this.arr_blocks[i][j]) {
            //判断是否相邻
            return false;
          } else if (j - 1 >= 0 && this.arr_blocks[i][j - 1] == this.arr_blocks[i][j]) {
            //判断是否相邻
            return false;
          }
        }
      }
    }

    return true;
  },
  //游戏结束动画
  actGameOver: function actGameOver() {
    var _this = this;

    var children = this.block_parent.children;

    var _loop = function _loop(i) {
      //闪烁
      cc.tween(children[i]).delay(1).blink(2, 4) // .repeat(4,cc.tween().by(0.2,{opacity: 255}).by(0.2,{opacity: 0}))
      .delay(0.1).call(function () {
        var _loop2 = function _loop2(j) {
          var childPos = children[i].getPosition();
          var type_block = children[i].getComponent("block").blockType; // this.createStar(childPos,type_block);

          _this.scheduleOnce(function () {
            // 这里的 this 指向 component
            if (children[i]) {
              this.createStar(childPos, type_block);
              children[i].destroy();
            }
          }, 0.1);
        };

        for (var j = 0; j < 1; j++) {
          _loop2(j);
        } // children[i].active = false;

      }, _this).start();
    };

    for (var i = 0; i < children.length; i++) {
      _loop(i);
    } // for(let i = 0; i < children.length; i++){
    //     children[i].destroy();          
    // }

  },
  //消除后移动块
  moveBlock_down: function moveBlock_down() {
    var _this2 = this;

    var children = this.block_parent.children;
    var f_time_big = 0.08;
    var f_time_1 = 0.08;

    for (var i = 0; i < children.length; i++) {
      var childPos = children[i].getPosition();
      var posBlock = this.getArrByPos(childPos); //空块

      var i_null = 0; //移动空块来设置时间

      for (var j = posBlock.x; j >= 0; j--) {
        if (this.arr_blocks[j][posBlock.y] == -1) {
          i_null++;
        }
      }

      cc.tween(children[i]).by(f_time_1, {
        position: cc.v2(0, -(this.black_size + this.black_interval) * i_null)
      }).call(function () {
        _this2.refreshArr();

        _this2.scheduleOnce(function () {
          // 这里的 this 指向 component
          this.moveBlock_Left();
        }, f_time_big + 0.02);

        if (_this2.isGameOver()) {
          console.log("game over");

          _this2.actGameOver();
        } else {
          console.log("game continue");
        }
      }).start(); // console.log("空块:",i_null);
    }
  },
  moveBlock_Left: function moveBlock_Left() {
    var _this3 = this;

    var children = this.block_parent.children;
    var f_time_big = 0.08;
    var f_time_1 = 0.08;

    for (var i = 0; i < children.length; i++) {
      var childPos = children[i].getPosition();
      var posBlock = this.getArrByPos(childPos); //空块

      var j_null = 0;

      for (var j = posBlock.y; j >= 0; j--) {
        if (posBlock.x != 0) {
          continue;
        }

        if (this.arr_blocks[posBlock.x][j] == -1) {
          j_null++;
        }
      }

      if (j_null > 0) {
        for (var iij = 0; iij < children.length; iij++) {
          var childPos_move = children[iij].getPosition();
          var posBlock_move = this.getArrByPos(childPos_move);

          if (posBlock_move.y == posBlock.y) {
            cc.tween(children[iij]).by(f_time_1, {
              position: cc.v2(-(this.black_size + this.black_interval) * j_null, 0)
            }).call(function () {
              _this3.refreshArr();

              if (_this3.isGameOver()) {
                console.log("game over1111");
              } else {
                console.log("game continue111");
              }
            }).start();
          }
        }
      }
    }
  },
  logArray: function logArray() {
    for (var i = this.black_num_height; i >= 0; i--) {
      console.log("数组", this.arr_blocks[i]);
    }
  },
  //屏幕触摸事件
  setTouch: function setTouch() {
    this.block_parent.on('touchstart', function (event) {
      var _this4 = this;

      var pos_start_world = event.getLocation(); //获得世界坐标，需要转化为相对于节点block_parent的坐标

      var pos_start_node = this.block_parent.convertToNodeSpaceAR(pos_start_world); // console.log(pos_start_node);
      //获得每一个块的区域

      var children = this.block_parent.children; //锤子动画
      //第二次触摸时如果当前块没有被选中则停止动画
      //先停止动画

      var _loop3 = function _loop3() {
        var click_anim = children[j].getComponent(cc.Animation);
        var state_anim = click_anim.getAnimationState("click_block");
        var Rerect = children[j].getBoundingBox();
        var iscuizi = children[j].getComponent("block").get_IsChuiZZi();
        var childPos = children[j].getPosition();
        var type_block = children[j].getComponent("block").blockType;

        if (Rerect.contains(pos_start_node)) {
          if (state_anim.isPlaying) {
            _this4.CanDesdroy(true);
          } else {
            _this4.CanDesdroy(false);
          } //锤子效果


          if (iscuizi) {
            console.log("可以锤了");

            var animChuiZi = _this4.node_ChuiZi.getComponent(cc.Animation);

            animChuiZi.play("ChuiZi");
            var ones = animChuiZi.play("ChuiZi");
            var test = j;
            ones.once('lastframe', function () {
              children[test].removeFromParent();
              _this4.node_ChuiZi.active = false;

              for (var count = 0; count < 5; count++) {
                _this4.createStar(childPos, type_block);
              }

              _this4.refreshArr();

              _this4.moveBlock_down();
            }, _this4);
          } else {
            console.log("换一个锤子🔨");

            _this4.NoNChuiZi();
          }
        }
      };

      for (var j = 0; j < children.length; j++) {
        _loop3();
      }

      for (var i = 0; i < children.length; i++) {
        var rect = children[i].getBoundingBox();

        if (rect.contains(pos_start_node)) {
          console.log("点击了第" + i + "个块,该块位置为", children[i].getPosition());

          if (this.node_ChuiZi.active) {
            //有锤子特效🔨
            this.node_ChuiZi.setPosition(children[i].getPosition());
            this.node_ChuiZi.x = children[i].x + 20;
            children[i].getComponent("block").set_IsChuiZZi(true);
            return;
          }

          this.touchOne(i);
        }
      }
    }, this);
  },
  //当前点击是否可以消除
  CanDesdroy: function CanDesdroy(isDestory) {
    var children = this.block_parent.children;
    var arr_destroy = [];

    for (var i = 0; i < children.length; i++) {
      var click_anim = children[i].getComponent(cc.Animation);
      var state_anim = click_anim.getAnimationState("click_block");

      if (isDestory) {
        if (state_anim.isPlaying) {
          arr_destroy.push(children[i]);
        }
      } else {
        click_anim.setCurrentTime(0, "click_block");
        click_anim.stop("click_block");
      }
    }

    if (arr_destroy.length > 1) {
      var blockType = arr_destroy[0].getComponent("block").blockType;

      for (var i = 0; i < arr_destroy.length; i++) {
        // console.log("当前可以被销毁de块有"+ arr_destroy.length+"个，他们分别为：",arr_destroy[i])
        arr_destroy[i].removeFromParent(); // arr_destroy[i].destroy();

        for (var j = 0; j < 5; j++) {
          this.createStar(arr_destroy[i].getPosition(), blockType);
        }
      }

      this.refreshArr();
      this.moveBlock_down(); // this.moveBlock_Left();
    }
  },
  //点中了一块S
  touchOne: function touchOne(touchone) {
    var children = this.block_parent.children; //点击块反复缩小放大,播放动画

    var click_anim = children[touchone].getComponent(cc.Animation);
    click_anim.play("click_block"); //同时选中改block相邻颜色的块

    var i_touch = touchone;
    var pos_touch = children[i_touch].getPosition(); //符合要求的块

    var arr_touch = [];

    for (var j = 0; j < children.length; j++) {
      if (j == i_touch) {
        continue;
      }

      var pos_j = children[j].getPosition(); //距离//判断是否相邻

      var Blocks_distance = (pos_touch.x - pos_j.x) * (pos_touch.x - pos_j.x) + (pos_touch.y - pos_j.y) * (pos_touch.y - pos_j.y);
      Blocks_distance = Math.sqrt(Blocks_distance); //    console.log("Blocks_distance:",Blocks_distance);

      if (Blocks_distance <= this.black_size + this.black_interval + 10) {
        if (children[j].getComponent("block").blockType == children[i_touch].getComponent("block").blockType) {
          var _click_anim = children[j].getComponent(cc.Animation);

          var state_anim = _click_anim.getAnimationState("click_block");

          if (state_anim.isPlaying) {
            //判断是否已经加入数组
            continue;
          } //播放动画


          _click_anim.play("click_block");

          arr_touch.push(j);
        }
      }
    }

    for (var i = 0; i < arr_touch.length; i++) {
      this.touchOne(arr_touch[i]);
    } // console.log("arr_touch:",arr_touch);

  },
  //创建星星，用于消除动画
  createStar: function createStar(pos_star, numType) {
    var star = cc.instantiate(this.prefab_star);
    star.parent = this.star_parent;
    star.setPosition(pos_star);
    star.getComponent("destoryStar").init(numType);
    this.random_Action(star);
  },
  //星星消除时的随机动画
  random_Action: function random_Action(star) {
    star.scale = 0.2 + Math.random() * 0.5; //星星移动位置

    var xx = 5 + Math.random() * 150;

    if (Math.random() > 0.5) {
      //向右
      xx = xx * -1;
    }

    var yy = 50 + Math.random() * 50;
    var moveOut = cc.tween().by(0.1, {
      position: cc.v2(xx, yy)
    });
    var moveIn = cc.tween().by(0.2, {
      position: cc.v2(xx, -yy - (100 + Math.random() * 100))
    }, {
      easing: "cubicIn"
    });
    var moveOutIn = cc.tween().then(moveOut).then(moveIn);
    var reRotation = cc.tween().repeat(30, cc.tween().by(0.01, {
      rotation: 90
    }));
    cc.tween(star).parallel(moveOutIn, reRotation) //.by(0.2 + Math.random()* 0.4,xx,-yy)
    .call(function () {
      star.destroy();
    }).start();
  },
  //按钮回调
  btn_callback: function btn_callback(sender, str) {
    if (str == "btn_play") {
      this.layerReady.active = false;
      this.layerGame.active = true;
      this.createAllBlock(); //还要加一个消除所有节点的方法
    } else if (str == "btn_zhanting") {
      this.layerZhanTing.active = true;
    } else if (str == "btn_close" || str == "btn_return") {
      this.layerZhanTing.active = false;
      this.layerGame.active = true;
    } else if (str == "btn_home") {
      //返回首页
      this.layerGame.active = false;
      this.layerReady.active = true;
      this.layerZhanTing.active = false;
      this.clean();
    } else if (str == "btn_restart") {
      this.clean();
      this.createAllBlock();
      this.layerZhanTing.active = false;
      this.layerGame.active = true;
    } //功能按钮只有在游戏未结束时调用


    if (!this.isGameOver()) {
      if (str == "btn_refresh") {
        this.refreshBlocks();
      } else if (str == "btn_ChuiZi") {
        this.BtnChuiZi();
      } else if (str == "btn_Tuya") {
        this.BtnTuya();
      }
    }
  },
  clean: function clean() {
    var children = this.block_parent.children;

    for (var i = 0; i < children.length; i++) {
      children[i].destroy();
    }
  },
  //刷新
  refreshBlocks: function refreshBlocks() {
    var _this5 = this;

    var children = this.block_parent.children;

    var _loop4 = function _loop4(i) {
      cc.tween(children[i]).to(0.2, {
        scale: 0.2
      }) // .delay(0.2)
      .call(function () {
        var randomNum = Math.floor(Math.random() * children.length);
        var Pos_child = children[i].getPosition();
        var Pos_random = children[randomNum].getPosition();
        children[i].setPosition(Pos_random);
        children[randomNum].setPosition(Pos_child);
        cc.tween(children[i]).to(0.2, {
          scale: 1
        }).start();
      }, _this5).start();
    };

    for (var i = 0; i < children.length; i++) {
      _loop4(i);
    }
  },
  BtnChuiZi: function BtnChuiZi() {
    this.node_ChuiZi.active = !this.node_ChuiZi.active;
    var children = this.block_parent.children;
    var randomNum = Math.floor(Math.random() * children.length);
    this.node_ChuiZi.setPosition(children[randomNum].getPosition());
    this.node_ChuiZi.x += 20;

    if (!this.node_ChuiZi.active) {
      this.NoNChuiZi();
    } else {
      children[randomNum].getComponent("block").set_IsChuiZZi(this.node_ChuiZi.active);
    } //暂停其他动画


    this.StopAnim();
  },
  //取消所有锤子特效
  NoNChuiZi: function NoNChuiZi() {
    var children = this.block_parent.children;

    for (var i = 0; i < children.length; i++) {
      children[i].getComponent("block").set_IsChuiZZi(false);
    }
  },
  //暂停动画
  StopAnim: function StopAnim() {
    var children = this.block_parent.children;

    for (var i = 0; i < children.length; i++) {
      var click_anim = children[i].getComponent(cc.Animation);
      var state_anim = click_anim.getAnimationState("click_block");

      if (state_anim.isPlaying) {
        click_anim.setCurrentTime(0, "click_block");
        click_anim.stop("click_block");
      }
    }
  },
  //涂鸦
  BtnTuya: function BtnTuya() {
    this.node_Tuya.active = !this.node_Tuya.active;
  } // update (dt) {},

});

cc._RF.pop();